import React, { Component, Fragment } from "react";
import { Form, Input, Popover, Progress } from "antd";
import { password as passwordReg } from "@/utils/regexp";
import styles from './Register.less';
const FormItem = Form.Item;

const passwordStatusMap = {
  ok: <div className={styles.success}>强度：强</div>,
  pass: <div className={styles.warning}>强度：中</div>,
  poor: <div className={styles.error}>强度：太短</div>,
};

const passwordProgressMap = {
  ok: 'success',
  pass: 'normal',
  poor: 'exception',
};

export default class LoginWithMsgFormItem extends Component {
  static defaultProps = {
    id: "password",
    disabled: false,
    confirm: false,
    initialValue: undefined,
    placeholder: "请输入密码",
    focus: false
  };

  constructor(props) {
    super(props);
    this.state = {
      confirmDirty: false,
      visible: false,
      help: '',
    };
    this.pswRef = React.createRef();
  }

  validateToNextPassword = (rule, value, callback) => {
    const { form } = this.props;
    if (value && this.state.confirmDirty) {
      form.validateFields(["confirm"], { force: true });
    }
    callback();
  };

  compareToFirstPassword = (rule, value, callback) => {
    const { form, id } = this.props;
    if (value && value !== form.getFieldValue(id)) {
      callback("两次密码输入不一致");
    } else {
      callback();
    }
  };

  handleConfirmBlur = e => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  getPasswordStatus = () => {
    const { form } = this.props;
    const value = form.getFieldValue('password');
    if (value && value.length > 9) {
      return 'ok';
    }
    if (value && value.length > 5) {
      return 'pass';
    }
    return 'poor';
  };

  renderPasswordProgress = () => {
    const { form } = this.props;
    const value = form.getFieldValue('password');
    const passwordStatus = this.getPasswordStatus();
    return value && value.length ? (
      <div className={styles[`progress-${passwordStatus}`]}>
        <Progress
          status={passwordProgressMap[passwordStatus]}
          className={styles.progress}
          strokeWidth={6}
          percent={value.length * 10 > 100 ? 100 : value.length * 10}
          showInfo={false}
        />
      </div>
    ) : null;
  };

  checkPassword = (rule, value, callback) => {
    const { visible, confirmDirty } = this.state;
    if (!value) {
      this.setState({
        help: '请输入密码！',
        visible: !!value,
      });
      callback('error');
    } else {
      this.setState({
        help: '',
      });
      if (!visible) {
        this.setState({
          visible: !!value,
        });
      }
      if (value.length < 6) {
        callback('error');
      } else {
        const { form } = this.props;
        if (value && confirmDirty) {
          form.validateFields(['confirm'], { force: true });
        }
        callback();
      }
    }
  };

  componentDidMount() {
    if (this.props.focus) this.pswRef.focus();
  }

  render() {
    const {
      form: { getFieldDecorator },
      id,
      disabled,
      initialValue,
      confirm,
      placeholder,
    } = this.props;
    const { help, visible } = this.state;
    return (
      <Fragment>
        {
          confirm ? (
            <FormItem help={help}>
              <Popover
                content={
                  <div style={{ padding: '4px 0' }}>
                    {passwordStatusMap[this.getPasswordStatus()]}
                    {this.renderPasswordProgress()}
                    <div style={{ marginTop: 10 }}>
                      请至少输入 6 个字符。请不要使用容易被猜到的密码。
                    </div>
                  </div>
                }
                overlayStyle={{ width: 240 }}
                placement="right"
                visible={visible}
              >
                {getFieldDecorator('password', {
                  rules: [
                    {
                      required: true,
                      message: "密码包括6-16位大小写字母数字",
                      pattern: passwordReg
                    },
                    {
                      validator: this.checkPassword,
                    },
                  ],
                })(
                  <Input
                  disabled={disabled}
                  className="login-input"
                  type="password"
                  ref={ref => (this.pswRef = ref)}
                  placeholder={placeholder}
                />
                )}
              </Popover>
            </FormItem>
          ) : (
            <FormItem>
              {getFieldDecorator(id, {
                initialValue: initialValue,
                rules: [
                  {
                    required: true,
                    message: "密码包括6-16位大小写字母数字",
                    pattern: passwordReg
                  },
                  {
                    validator: this.validateToNextPassword
                  }
                ]
              })(
                <Input
                  disabled={disabled}
                  className="login-input"
                  type="password"
                  ref={ref => (this.pswRef = ref)}
                  placeholder={placeholder}
                />
              )}
            </FormItem>
          )
        }

        {confirm && (
          <FormItem>
            {getFieldDecorator("confirm", {
              rules: [
                {
                  required: true,
                  message: "请再次输入密码"
                },
                {
                  validator: this.compareToFirstPassword
                }
              ]
            })(
              <Input
                disabled={disabled}
                className="login-input"
                placeholder="请再次输入密码"
                type="password"
                onBlur={this.handleConfirmBlur}
              />
            )}
          </FormItem>
        )}
      </Fragment>
    );
  }
}
